package ru.alperez.gpsdub.widget;

import ru.alperez.gpsdub.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ViewFlipper;

public class SlidingViewFlipper extends ViewFlipper {

	private Animation nextOldAnimation;
	private Animation nextNewAnimation;
	private Animation prevOldAnimation;
	private Animation prevNewAnimation;

	public SlidingViewFlipper(Context context) {
		super(context);
		if (!isInEditMode())
			initAnimations(context);
	}

	public SlidingViewFlipper(Context context, AttributeSet attrs) {
		super(context, attrs);
		if (!isInEditMode())
			initAnimations(context);
	}

	private void initAnimations(Context context) {
		nextNewAnimation = AnimationUtils.loadAnimation(context, R.anim.fly_from_right);
		nextOldAnimation = AnimationUtils.loadAnimation(context, R.anim.fly_to_left);
		prevNewAnimation = AnimationUtils.loadAnimation(context, R.anim.fly_from_left);
		prevOldAnimation = AnimationUtils.loadAnimation(context, R.anim.fly_to_right);
	}

	@Override
	public void showNext() {
		setInAnimation(nextNewAnimation);
		setOutAnimation(nextOldAnimation);
		super.showNext();
	}

	public void showNext(int step) {
		setInAnimation(nextNewAnimation);
		setOutAnimation(nextOldAnimation);
		super.setDisplayedChild(super.getDisplayedChild() + step);
	}

	public void showPrevious(int step) {
		setInAnimation(prevNewAnimation);
		setOutAnimation(prevOldAnimation);
		super.setDisplayedChild(super.getDisplayedChild() - step);
	}

	@Override
	public void showPrevious() {
		setInAnimation(prevNewAnimation);
		setOutAnimation(prevOldAnimation);
		super.showPrevious();
	}

	public void gotoSpecific(int whichChild) {
		setInAnimation(null);
		setOutAnimation(null);
		super.setDisplayedChild(whichChild);
	}

	@Override
	protected void onDetachedFromWindow() {
		try {
			super.onDetachedFromWindow();
		} catch (IllegalArgumentException e) {
			stopFlipping();
		}
	}
}